import asyncio
import socketio
import uvicorn

loop = asyncio.get_event_loop()

sio = socketio.AsyncClient()
sio_server = socketio.Server()
app = socketio.WSGIApp(sio_server, static_files={
    '/': 'latency.html',
    '/static': 'static'
})

"""
async def send_ping():
    global start_timer
    start_timer = time.time()
    await sio.emit('ping_from_client')
    

async def send_data(data):
    print('connected to server')
    await sio.emit('data_from_client', data)
"""

@sio.event
async def connect():
    print('connected to server')
    await sio.emit('ping_from_client')

@sio.event
async def pong_from_server():
    #global start_timer
    #latency = time.time() - start_timer
    #print('latency is {0:.2f} ms'.format(latency * 1000))
    #await sio.sleep(1)
    # 启动自己的服务器
    #global sio_server
    #global app

    #uvicorn.run(app, host='127.0.0.1', port=5000)
    pass

@sio.event
async def receipt_from_server(sid):
    # 将数据回执转给服务器
    await sio_server.emit('receipt_from_server', room=sid)

@sio_server.event
async def ping_from_client(sid):
    await sio_server.emit('pong_from_server', room=sid)

@sio_server.event
async def data_from_client(sid, data):
    # 将接收的data用客户端发送
    await sio.emit('data_from_client', data)

async def start_server():
    await sio.connect('http://localhost:6666')
    await sio.wait()
    await uvicorn.run(app, host='127.0.0.1', port=5000)



if __name__ == '__main__':
    loop.run_until_complete(start_server())
